package com.pactera.asmp.server.common.logprint.utils;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.UnknownHostException;

/**
 * <p>Class: com.lzq.plugin.logprint.utils.Log</p>
 * <p>Description: </p>
 * <pre>
 *
 * </pre>
 *
 * @author lv zhiqiang
 * @date 2019/7/23/11:39
 */
public class Log {

    public static void i(String tag, String msg) {
        if(tag == null || tag.equals("")){
            System.out.println(msg);
            return;
        }
        System.out.println(tag + " : " + msg);
    }

    public static void w(String tag, String msg) {
        if(tag == null || tag.equals("")){
            System.out.println(msg);
            return;
        }
        System.err.println(tag + " : " + msg);
    }

    public static void e(String tag, String msg) {
        if(tag == null || tag.equals("")){
            System.err.println(msg);
            return;
        }
        System.err.println(tag + " : " + msg);
    }

    public static void e(String tag, String msg, Throwable e) {
        System.err.println(tag + " : " + msg + " ;Throwable getStackTraceString:"+getStackTraceString(e));
    }

    public static void d(String tag, String msg) {
        if(tag == null || tag.equals("")){
            System.out.println(msg);
            return;
        }
        System.out.println(tag + " : " + msg);
    }

    /**
     * 323     * Handy function to get a loggable stack issue from a Throwable
     * 324     * @param tr An exception to log
     * 325
     */
    public static String getStackTraceString(Throwable tr) {
        if (tr == null) {
            return "";
        }

        // This is to reduce the amount of log spew that apps do in the non-error
        // condition of the network being unavailable.
        Throwable t = tr;
        while (t != null) {
            if (t instanceof UnknownHostException) {
                return "";
            }
            t = t.getCause();
        }

        StringWriter sw = new StringWriter();
        PrintWriter pw = new FastPrintWriter(sw, false, 256);
        tr.printStackTrace(pw);
        pw.flush();
        return sw.toString();
    }
}
